$(function() {
    loadStyleTable();
    
    $('#setTableTitle').blur(function(){
      freshPreview();
    });
    
    
	$('.tab2').click(function(e) {
        freshPreview();
	});
	
	$('#new_style_design_panel').dialog({
        autoOpen: false,
        resizable: false,
        modal: true,
        width: 800,
        title: "新建样式"
   	});
   	
   	$('#prompt_preview_div').dialog({
        autoOpen: false,
        resizable: false,
        modal: true,
        width: 800,
        title: "新建样式预览"
   	});
});


function loadStyleTable() {
  $("#style_list_table").jqGrid({
    url: "styles.action",
    datatype: "json",
    height: 200,
    width: 905,
    colNames: ["样式编码", "样式名称", "宝贝图片大小", "是否显示促销标签", "是否显示购买按钮","","","","","","","","","","","","","","","","","","","","","","","",""],
	colModel: [{name: "STYLE_ID",index: "STYLE_ID",align:"center",sortable: false},
			   {name: "STYLE_NAME",index: "STYLE_NAME",align:"center",sortable: false},
			   {name: "NUM_PER_LINE_DESC",index: "NUM_PER_LINE_DESC",align:"center",sortable: false},
			   {name: "IS_PROMOTION_LABEL_DESC",index: "IS_PROMOTION_LABEL_DESC",align:"center",sortable: false},
			   {name: "IS_BUY_BUTTON_DESC",index: "IS_BUY_BUTTON_DESC",align:"center",sortable: false},
				{name: "TEMPLET_ID",index: "TEMPLET_ID",align:"center",hidden:true},
				{name: "SKIN_ID",index: "SKIN_ID",align:"center",hidden:true},
				{name: "NUM_PER_LINE",index: "NUM_PER_LINE",align:"center",hidden:true},
				{name: "STATIC_FLAG",index: "STATIC_FLAG",align:"center",hidden:true},
				{name: "KEY_WORDS",index: "KEY_WORDS",align:"center",hidden:true},
				{name: "IS_PROMOTION_LABEL",index: "IS_PROMOTION_LABEL",align:"center",hidden:true},
				{name: "PROMOTION_LABEL",index: "PROMOTION_LABEL",align:"center",hidden:true},
				{name: "IS_TITLE",index: "IS_TITLE",align:"center",hidden:true},
				{name: "IS_PRICE",index: "IS_PRICE",align:"center",hidden:true},
				{name: "PRICE_STYLE",index: "PRICE_STYLE",align:"center",hidden:true},
				{name: "PRICE_LABEL",index: "PRICE_LABEL",align:"center",hidden:true},
				{name: "MARKET_PRICE",index: "MARKET_PRICE",align:"center",hidden:true},
				{name: "PRICE_TEXT",index: "PRICE_TEXT",align:"center",hidden:true},
				{name: "IS_PRICE_STRIKE",index: "IS_PRICE_STRIKE",align:"center",hidden:true},
				{name: "IS_BUY_BUTTON",index: "IS_BUY_BUTTON",align:"center",hidden:true},
				{name: "BUY_BUTTON",index: "BUY_BUTTON",align:"center",hidden:true},
				{name: "IS_FAV",index: "IS_FAV",align:"center",hidden:true},
				{name: "IS_WANGWANG",index: "IS_WANGWANG",align:"center",hidden:true},
				{name: "WANGWANG",index: "WANGWANG",align:"center",hidden:true},
				{name: "PRO4IPRO",index: "PRO4IPRO",align:"center",hidden:true},
				{name: "STYLE_NAME",index: "STYLE_NAME",align:"center",hidden:true},
				{name: "PROMOTION_POSITION",index: "PROMOTION_POSITION",align:"center",hidden:true},
				{name: "BC_FLAG",index: "BC_FLAG",align:"center",hidden:true},
				{name: "LAYOUT",index: "LAYOUT",align:"center",hidden:true}
				],
    viewrecords: true,
    rowNum: 5,
    rowList: [5, 10],
    loadComplete: function () {
        setCellHeight('style_list_table',30);
        setStyleTableSelection();
        //freshPreview();
    },
    onSelectRow: function(rowid, status) {
      	freshPreview();
    },
    jsonReader: {
      root: "dataset",
      page: "pager.curPageNo",
      total: "pager.totalPages",
      records: "pager.totalCount",
      repeatitems: false
    },
    prmNames: {
      rows: "pager.pageSize",
      page: "pager.curPageNo",
      sort: "pager.orderBy",
      order: "pager.order"
    },
    pager: "#style_list_pager",
    caption: "选择已有样式"
  });
}

function setCellHeight(gridName,height) { 
    var ids = $("#"+gridName).getDataIDs(); 
    for (var i = 0; i < ids.length; i++) { 
      var cl = ids[i]; 
      $("#"+gridName).setRowData(ids[i],false, {height: height}); 
    } 
}

function setStyleTableSelection() {
  var records = $("#style_list_table").jqGrid("getGridParam", "records");
  if(records==null){
    return;
  }
  if(records > 0){
    $("#style_list_table").setSelection(1);
  }else{
  }
}

function init_templet() {
	if(empty(buildItemJsonStr())) {
		alert("请先选择要推广的宝贝！！！");
		$('.tab1').click();
		return;
	}
	var init_v = $("#init_indicator").val();
	if(init_v=="init") display_templet("templet_1");
	else $('#new_style_design_panel').dialog("open");
}

function display_templet(templetName) {
	$('#new_style_container').html("<span class='red fb f22'>正在加载，请稍等...</span>");
	
	var tname = templetName===undefined?"templet_1":templetName;
	var html = $.ajax({url:"templet.action",data:{"t":tname},async:false}).responseText;
	$("#new_style_container").html(html);
	
	$('#new_style_design_panel').dialog("open");
}

function preview(){
	var itemStr = buildItemJsonStr();
	if(itemStr===''){
		$('#prompt_preview_div').html("<div class='red fb f22'>请在第1步选择您要推广的宝贝</div>");
		$('#prompt_preview_div').dialog("open");
	    return;
	}
    
    var param = getStyle();
    param["itemsStr"] = itemStr;
    $.post("preview.action", param,
    	function(data,status) {
    		$('#prompt_preview_div').html(data.result);
    		$('#prompt_preview_div').dialog("open");
    	}, 
    	"json"
    );
}

function persist(){
    var param = getStyle();
    $.post("persist.action", param,
		function(data,status){
			if(Number(data.result.code)<0){
			    alert(data.result.msg);
			}else{
				alert("样式保存成功！！！");
				$('#new_style_design_panel').dialog("close");
			  	$("#style_list_table").trigger("reloadGrid");
			}
		}, 
		"json"
	);
}

function cancel(){
	$('#new_style_design_panel').dialog("close");
}

function getStyle(){
	var buy_button = $('input[name=buy_button]:checked').val();
    var price_label = $('input[name=price_label]:checked').val();
    var num_per_line = $('input[name=num_per_line]:checked').val()
    var layoutPosition = $('input[name=promotion_position]:checked').val();
    var promotion_label= $('input[name=promotion_label]:checked').val()+"_"+layoutPosition+"_"+num_per_line;
    var is_price_strike = $('input[name=is_price_strike]:checked').val();
    if(is_price_strike!='1') is_price_strike ='0';
    
    var params = {
     "style.TEMPLET_ID":$("input[name='t']:checked").val(),
     "style.SKIN_ID":$("input[name='skin_id']:checked").val(),
     "style.NUM_PER_LINE":$("input[name='num_per_line']:checked").val(),
     "style.STATIC_FLAG":$("input[name='static_flag']:checked").val(),
     "style.KEY_WORDS":$('#key_words').val(),
     "style.IS_PROMOTION_LABEL":$('input[name=is_promotion_label]:checked').val(),
     "style.PROMOTION_LABEL":promotion_label,
     "style.IS_TITLE":$('input[name=is_title]:checked').val(),
     "style.IS_PRICE":$('input[name=is_price]:checked').val(),
     "style.PRICE_STYLE":$('input[name=price_style]:checked').val(),
     "style.PRICE_LABEL":price_label,
     "style.MARKET_PRICE":$('#market_price').val(), 
     "style.PRICE_TEXT":$('#price_text').val(),
     "style.IS_PRICE_STRIKE":is_price_strike,
     "style.IS_BUY_BUTTON":$('input[name=is_buy_button]:checked').val(),
     "style.BUY_BUTTON":buy_button,
     "style.IS_FAV":$('input[name=is_fav]:checked').val(),
     "style.IS_WANGWANG":$('input[name=is_wangwang]:checked').val(),
     "style.WANGWANG":$('#wangwang').val(),
     "style.PRO4IPRO":$('input[name=pro4ipro]:checked').val(),
     "style.STYLE_NAME":$('#styleName').val(),
     "style.PROMOTION_POSITION":layoutPosition,
     "style.BC_FLAG":$("input[name='is_b_c']").val(),
     "style.LAYOUT":getLayout(),
     "title":$('#setTableTitle').val(),
    };
    
 	return params;
}

function getLayout(){
	var result = "";
  	var is_buy_button =$('input[name=is_buy_button]:checked').val();
  	var is_title =$('input[name=is_title]:checked').val();
  	var is_price =$('input[name=is_price]:checked').val();
  
  	if(is_title=='1') result+="item_title_code";
  	if(is_price=='1') result+=",item_price_code";
  	if(is_buy_button=='1') result+=",item_buy_button_code";
  	if(result.indexOf(',')===0)
    	result=result.substring(1,result.length);

  	return result;
}

function getChooseStyle(){
	var  rowid = $("#style_list_table").getGridParam( "selrow" ); 
	if (rowid === null) {
        return {};
    }
    var ret = $("#style_list_table").jqGrid("getRowData", rowid);
    
    var params = {
		"style.TEMPLET_ID":ret.TEMPLET_ID,
		"style.SKIN_ID":ret.SKIN_ID,
		"style.NUM_PER_LINE":ret.NUM_PER_LINE,
		"style.STATIC_FLAG":ret.STATIC_FLAG,
		"style.KEY_WORDS":ret.KEY_WORDS,
		"style.IS_PROMOTION_LABEL":ret.IS_PROMOTION_LABEL,
		"style.PROMOTION_LABEL":ret.PROMOTION_LABEL,
		"style.IS_TITLE":ret.IS_TITLE,
		"style.IS_PRICE":ret.IS_PRICE,
		"style.PRICE_STYLE":ret.PRICE_STYLE,
		"style.PRICE_LABEL":ret.PRICE_LABEL,
		"style.MARKET_PRICE":ret.MARKET_PRICE,
		"style.PRICE_TEXT":ret.PRICE_TEXT,
		"style.IS_PRICE_STRIKE":ret.IS_PRICE_STRIKE,
		"style.IS_BUY_BUTTON":ret.IS_BUY_BUTTON,
		"style.BUY_BUTTON":ret.BUY_BUTTON,
		"style.IS_FAV":ret.IS_FAV,
		"style.IS_WANGWANG":ret.IS_WANGWANG,
		"style.WANGWANG":ret.WANGWANG,
		"style.PRO4IPRO":ret.PRO4IPRO,
		"style.STYLE_NAME":ret.STYLE_NAME,
		"style.PROMOTION_POSITION":ret.PROMOTION_POSITION,
		"style.BC_FLAG":ret.BC_FLAG,
		"style.LAYOUT":ret.LAYOUT,
        "title":$('#setTableTitle').val(),
    };
 	return params;
}

//刷新重新加载预览
function freshPreview(){
    var params = getChooseStyle();
    var itemStr = buildItemJsonStr();
	if(itemStr===''){
		$('#choose_style_preview').html("<div class='red fb f22'>请在第1步选择您要推广的宝贝</div>")
	    return;
	}
	params["itemsStr"] = itemStr;
	
    $('#choose_style_preview').html("<br />正在加载，请稍等...<br />");
    $.post("preview.action", params,
    	function(data,status) {
    		$('#choose_style_preview').html(data.result);
    	}, 
    	"json"
    );
}

function validate_tab0() {
	if(empty(buildItemJsonStr())) {
		alert("您尚未选择安装宝贝！！！");
		return false;
	}
	return true;
}